package com.test.testauth.fliter;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @author ：wang qiang
 * @date ：Created 2024/7/31 15:46
 * @description：日志追踪拦截器
 */
public class LogFliter implements HandlerInterceptor {

    private static final String TRACE_ID = "traceId";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 使用UUID自动生成链路ID
        String tid = UUID.randomUUID().toString().replace("-", "");
        // 客户端可以传入链路ID，需要唯一性
        String traceId = request.getHeader(TRACE_ID);
        if (StringUtils.isNotEmpty(traceId)) {
            MDC.put(TRACE_ID, traceId);
        }else{
            MDC.put(TRACE_ID, tid);
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        MDC.remove(TRACE_ID);
    }
}
